package com.seecen.HJM.controller;


import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.util.RandomUtil;
import com.seecen.HJM.model.dto.CaptchaCodeDto;
import com.seecen.HJM.result.DataVo;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/*
1.先获取一个验证码
2.验证码与用户信息一并发到登录请求中
3.验证码验证  不通过

 */
@Slf4j
@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {
    public static final String Captcha_Code = "Captcha_Code";
    @Resource
    public JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    /*
    获取算数型验证码
    @return
     */

    //原验证码接口
    @GetMapping("/arithmetic")
    public void getArithmetic(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.设置验证码的参数，宽，高 字符数量（默认俩个字符计算）
        ShearCaptcha shearCaptcha = new ShearCaptcha(200, 48, 2, 2);
        //2.设置验证码的生成器 为算数验证码
        shearCaptcha.setGenerator(new MathGenerator(1));
        //3，创建验证码
        shearCaptcha.createCode();
        log.info(shearCaptcha.getCode());
//获取session存入验证码到session
        HttpSession session = request.getSession();

        CaptchaCodeDto captchaCodeDto = new CaptchaCodeDto();
        captchaCodeDto.setCode(shearCaptcha.getCode());
        //设置一分钟验证码过期时间
        LocalDateTime expDate = LocalDateTime.now().plusMinutes(1);
        captchaCodeDto.setExpDate(expDate);

        session.setAttribute(Captcha_Code, captchaCodeDto);

        //4.输出验证码图片
        shearCaptcha.write(response.getOutputStream());
        //会将验证码存储在session并且输出验证码图片到客户端

    }


    @PostMapping("/emailCode")
    public DataVo getEmailCode(@RequestParam
                               @Valid
                               @Email(message = "邮件格式不正确") String email) {
        //验证码生成4位数字字符串  hutool包
        String code = RandomUtil.randomString(4);
        //验证码标题
        String subject = "【思成科技】验证码";
        //验证码的内容格式与具体内容
        String content = "您的验证码为：" + code + "有效期为5分钟，请勿泄露验证码";
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            //邮件的发送人
            helper.setFrom(username);
            //邮件接收人
            helper.setTo(email);
            //设置邮件标题与内容
            helper.setSubject(subject);
            helper.setText(content);
            javaMailSender.send(mimeMessage);

            redisTemplate.opsForValue().set("email:code:" + email, code, 5, TimeUnit.MINUTES);
            log.info("向邮箱{}发送验证码成功", email);
        } catch (Exception e) {
            log.error("验证码发送失败:{}", e.getMessage());
            return DataVo.error("验证码发送失败");
        }

        return DataVo.success(email);
    }
}
